package com.yuda.campsite.controller;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.io.IOException;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.yuda.common.core.utils.file.OssFileUtils;
import io.netty.buffer.ByteBufInputStream;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.yuda.common.log.annotation.Log;
import com.yuda.common.log.enums.BusinessType;
import com.yuda.common.security.annotation.PreAuthorize;
import com.yuda.campsite.domain.CampsiteWorkTeacher;
import com.yuda.campsite.service.ICampsiteWorkTeacherService;
import com.yuda.common.core.web.controller.BaseController;
import com.yuda.common.core.web.domain.AjaxResult;
import com.yuda.common.core.utils.poi.ExcelUtil;
import com.yuda.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 【请填写功能名称】Controller
 *
 * @author wyn
 * @date 2021-12-06
 */
@RestController
@RequestMapping("/teacher")
@Slf4j
public class CampsiteWorkTeacherController extends BaseController
{
    @Autowired
    private ICampsiteWorkTeacherService campsiteWorkTeacherService;
    @Resource
    private OSS oss;
    public static boolean checkFileSize(long len,int size,String unit){
        double fileSize =0;
        if ("B".equals(unit.toUpperCase())){
            fileSize=(double) len;
        }else if ("K".equals(unit.toUpperCase())){
            fileSize=(double) len/1024;
        }else if ("M".equals(unit.toUpperCase())){
            fileSize=(double) len/1048576;
        }else if ("G".equals(unit.toUpperCase())){
            fileSize=(double) len/1073741824;
        }if (fileSize>size){
            return false;
        }
        return true;
    }

    /**
     * 查询【请填写功能名称】列表
     */
 //   @PreAuthorize(hasPermi = "common:teacher:list")
    @GetMapping("/list")
    public TableDataInfo list( CampsiteWorkTeacher campsiteWorkTeacher)
    {
        startPage();
        List<CampsiteWorkTeacher> list = campsiteWorkTeacherService.selectCampsiteWorkTeacherList(campsiteWorkTeacher);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize(hasPermi = "common:teacher:export")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CampsiteWorkTeacher campsiteWorkTeacher) throws IOException
    {
        List<CampsiteWorkTeacher> list = campsiteWorkTeacherService.selectCampsiteWorkTeacherList(campsiteWorkTeacher);
        ExcelUtil<CampsiteWorkTeacher> util = new ExcelUtil<CampsiteWorkTeacher>(CampsiteWorkTeacher.class);
        util.exportExcel(response, list, "teacher");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
  //  @PreAuthorize(hasPermi = "common:teacher:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        long l = Long.parseLong(id);
        return AjaxResult.success(campsiteWorkTeacherService.selectCampsiteWorkTeacherById(l));
    }

    /**
     * 新增【请填写功能名称】
     */
   // @PreAuthorize(hasPermi = "campsite:teacher:add")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid  @RequestBody  CampsiteWorkTeacher campsiteWorkTeacher)
    {
        List<String> stringList = campsiteWorkTeacherService.ChaXunZuoYe(campsiteWorkTeacher.getCampId());
        if (stringList!=null) {
            for (String s : stringList) {
                if (s.equals(campsiteWorkTeacher.getWorkName())){
                    return AjaxResult.error("作业名称不能重复");
                }
            }
        }
        /**设置创建时间就是第一次加入的时间*/
        Date date =new Date(System.currentTimeMillis());
        campsiteWorkTeacher.setCreateTime(date);
        /**查询此时营地中有几个作业(去掉删除的作业)*/
        Integer integer = campsiteWorkTeacherService.ZuoYeNum(String.valueOf(campsiteWorkTeacher.getCampId()));
        /**将下次新建的作业中的stu_work_num属性设置为加1*/
        campsiteWorkTeacher.setWorkNum(Long.valueOf(integer+1));
        return toAjax(campsiteWorkTeacherService.insertCampsiteWorkTeacher(campsiteWorkTeacher));
    }

    /**
     * 修改【请填写功能名称】
     */
   // @PreAuthorize(hasPermi = "common:teacher:edit")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CampsiteWorkTeacher campsiteWorkTeacher)
    {
         /**编辑作业题目时候也不能添加相同的名字*/
        List<String> stringList = campsiteWorkTeacherService.ChaXunZuoYe(campsiteWorkTeacher.getCampId());
        if (stringList!=null && campsiteWorkTeacher.getWorkName()!=null) {
            for (String s : stringList) {
                if (campsiteWorkTeacher.getWorkName().equals(s)){
                    return AjaxResult.error("作业名称不能相同");
                }
            }
        }
        /**设置自动修改时间*/
        Date date =new Date();
        campsiteWorkTeacher.setUpdateTime(date);
        return toAjax(campsiteWorkTeacherService.updateCampsiteWorkTeacher(campsiteWorkTeacher));
    }

    /**
     * 删除【请填写功能名称】
     */
  //  @PreAuthorize(hasPermi = "common:teacher:remove")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        /**删除作业之后必须将这次作业之后的其他作业的题号按顺序修改*/

        return toAjax(campsiteWorkTeacherService.deleteCampsiteWorkTeacherByIds(ids));
    }
    /**教师上传作业pdf,word,excel等文件，需要使用文件数组*/
    @PostMapping("/UploadWork")
    public AjaxResult UploadWork(MultipartFile[] multipartFile){
      /**用来装载这些url，多的之间使用,隔开*/
       List<String> list =new ArrayList<>();
        /**首先进行判空，老一套了*/
        if (multipartFile==null||multipartFile.length<=0){
        return AjaxResult.error("请不要上传空文件");
        }
        /**判断文件的大小不能超过十个*/
        if (multipartFile.length>10){
            return AjaxResult.error("请不要上传大于10个文件");
        }
        /**遍历文件进oss*/
        for (int i=0;i<multipartFile.length;i++) {
            MultipartFile multipartFile1 = multipartFile[i];
            /**如果大于100M则不给他上传*/
            boolean m = checkFileSize(multipartFile1.getSize(), 100, "M");
            if (m){
                log.info("开始上传文件了");
                String originalFilename = multipartFile1.getOriginalFilename();
                String fileName = OssFileUtils.generateFileName(multipartFile1);
                String url =null;
                String s = UUID.randomUUID().toString().trim().replaceAll("-", "");
                String objectName = s +"work/" +originalFilename;
                String bucketName = "campiste";
                try {
                    oss.putObject(bucketName,objectName,new ByteArrayInputStream(multipartFile1.getBytes()));
                    url = "http://campiste.oss-cn-beijing.aliyuncs.com" + "/" + objectName;
                    list.add(url);
                } catch (IOException e) {
                    e.printStackTrace();
                    log.info("第"+i+"文件上传失败");
                }

            }else {
                return AjaxResult.error("文件大小大于100M,请重新选择小的文件上传");
            }
        }
        /**将所得的URL集合转换为大的字符串*/
        String join = StringUtils.join(list, ",");
       return AjaxResult.success(join );
    }
    @PostMapping("/delete")
   /**作业的逻辑删除*/
   public AjaxResult WorkLd(@RequestParam(value = "campId")String campId,
                            @RequestParam(value = "id") Integer id){
       campsiteWorkTeacherService.WorkLuoJi(campId, id);
       return AjaxResult.success("删除成功");
   }
   /**修改作业的新街口*/
   @PostMapping("/Update")
    public AjaxResult Update (@RequestBody CampsiteWorkTeacher campsiteWorkTeacher){
       /**编辑作业题目时候也不能添加相同的名字*/
       List<String> stringList = campsiteWorkTeacherService.ChaXunZuoYe(campsiteWorkTeacher.getCampId());
        /**查询此次作业名称(修改的时候把自己去掉)*/
       String s1 = campsiteWorkTeacherService.DanGeZuoYe(campsiteWorkTeacher.getId());
       /**如果这个营地的总题号包含这个题目名称就把它去除掉，当然是肯定包含的*/
       if (stringList.contains(s1)){
           /**把自己的题号去除，然后遍历剩下的元素，如果发现是一样的，就提示不能一样*/
           List<String> collect = stringList.stream().filter(x -> !x.equals(s1)).collect(Collectors.toList());
           if (collect!=null && campsiteWorkTeacher.getWorkName()!=null) {
               for (String s : collect) {
                   if (campsiteWorkTeacher.getWorkName().equals(s)){
                       return AjaxResult.error("作业名称不能相同");
                   }
               }
           }
       }

       int i = campsiteWorkTeacherService.updateCampsiteWorkTeacher(campsiteWorkTeacher);
       return AjaxResult.success("编辑作业成功");
   }
   @PostMapping("/NewDelete")
    public AjaxResult NewDelete(@RequestBody CampsiteWorkTeacher campsiteWorkTeacher){
       /**删除之前必须判断这个作业有没有人提交过
        * 如果有人提交则不能删除*/
       String s = campsiteWorkTeacherService.IsStudentTiJiao(campsiteWorkTeacher.getId());
       if (s==null){
           /**删除此次作业之后必须将这次作业之后的题号按顺序修改*/
       /**首先查询当前营地下面的所有作业名称，这个是唯一的*/
       List<String> stringList = campsiteWorkTeacherService.ChaXunZuoYe(campsiteWorkTeacher.getCampId());
       /**如果原来的集合就是1个的话直接删除*/
       if ( stringList.size()==1){
           campsiteWorkTeacherService.deleteCampsiteWorkTeacherById(campsiteWorkTeacher.getId());
         return AjaxResult.success("删除成功");
       }
       /**再次找到这个题目名在这个集合的位置*/
       int i = stringList.indexOf(campsiteWorkTeacher.getWorkName());
       /**如果这题是最后一个也是直接删*/
       int ld =i+1;
       if (ld==stringList.size()){
           campsiteWorkTeacherService.deleteCampsiteWorkTeacherById(campsiteWorkTeacher.getId());
           return AjaxResult.success("删除成功");
       }
       /**将这个题目下面的所有题目的题号减一。加入数据库*/
       for (int a=i;a<stringList.size()-1;a++){
           /**获取当前题目的下一题的题目名*/
           String workname = stringList.get(a + 1);
           /**获取需要删除的题目也就是当前题目的下一题的题号*/
           Integer worknumber =a+1;
           campsiteWorkTeacherService.XiuGaiZuoYeTiHao(worknumber,workname,campsiteWorkTeacher.getCampId());
       }
       /**然后再执行删除*/
       campsiteWorkTeacherService.deleteCampsiteWorkTeacherById(campsiteWorkTeacher.getId());
       return  AjaxResult.success("删除成功");
       }
       else {
        return AjaxResult.error("此次作业已经有学生提交了，不可删除");
       }
   }
}
